package com.mulanweb.api.module.controller.event;

import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.mulanweb.api.module.controller.BaseController;
import com.mulanweb.api.module.model.*;
import com.mulanweb.db.common.Constant;
import com.mulanweb.db.common.WxParaFormatter;
import com.mulanweb.handler.GetHandler;
import com.mulanweb.handler.wechat.UserHandler;
import com.mulanweb.validator.annotation.ValidateFile;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2016/9/26.
 */
@ValidateFile
public class PhotographyController extends BaseController {

    public void startVote() {
        String openId = super.getSessionAttr("openId"); //"oULNBwOvt_D2A_8se1bQOQ06ky0w"; //
        User user = User.dao.findFirst("SELECT * FROM `user` WHERE open_id = ? AND status_id = 1", openId);
        Long targetId = getParaToLong("targetId");
        if (user != null && UserHandler.userNotNull(openId)) {
            //开始投票
            PhotographyContent photographyContent = PhotographyContent.dao.findById(targetId);
            if(photographyContent != null){
                Event event = Event.dao.findFirst("SELECT * FROM event WHERE id =3 AND start_time <= NOW() AND NOW() < end_time");
                if(event != null){
                    //活动合法，开始投票
                    startVote3(user.getId(),targetId);
                }else{
                    //活动非法，返回错误
                    returnJson(0, "活动未开始,或已结束");
                    return;
                }
            }else{
                renderData(0, "活动无效");
            }
        } else {
            //未关注
            renderData(2, "授权失败，请关注《新途微助手》后再试");
        }
    }

    private synchronized void startVote3(Long userId, Long tagetId){
        PhotographyVoteCount photographyVoteCount = PhotographyVoteCount.dao.findFirst("SELECT * FROM photography_vote_count WHERE TO_DAYS(create_time) = TO_DAYS(NOW()) AND user_id = ?", userId);
        if(photographyVoteCount !=null){
            renderData(0, "您今天已投票,请明天再来");
        }else{
            photographyVoteCount = new PhotographyVoteCount();
            photographyVoteCount.setTargetId(tagetId);
            photographyVoteCount.setUserId(userId);
            photographyVoteCount.setCreateTime(new Date());
            if(photographyVoteCount.save()){
                renderData(1, "投票成功");
            }else{
                renderData(0, "投票失败");
            }
        }

    }

    public void route()  throws IOException{
        HttpServletRequest request = super.getRequest();
        HttpServletResponse response = super.getResponse();
        if (StrKit.notBlank(request.getParameter("code"))) {
            String code = request.getParameter("code");
            String para = GetHandler.get(Constant.WeChatFinalValue.getWebAuthorizeAccessToken(code));
            Map<String, String> mapPara = WxParaFormatter.jsonToMap(para);
            if (mapPara.containsKey("errcode")) {
                //returnJson(0, "授权出错，请重试");
                renderData(2, "授权失败，请关注《新途微助手》后再试");
            } else {
                String state = request.getParameter("state");
                String openId = mapPara.get("openid"); // "oULNBwOvt_D2A_8se1bQOQ06ky0w"; //
                super.setSessionAttr("openId", openId);
                //授权成功，跳转到主页面
                redirect("/event/photography/index.jsp");
                /*if ("?".equals(state)) {

                }*/
            }
        }
    }

    public void getPhotographyContent(){
        List<PhotographyContent> list = PhotographyContent.dao.find("SELECT pc.* FROM photography_content pc WHERE event_id=3 ORDER BY( SELECT COUNT(*) FROM photography_vote_count WHERE target_id = pc.id) DESC");
        List<Map> listMap = new ArrayList<>();
        int i=1;//排名
        for(PhotographyContent pc : list){
            Integer voteCount = 0 ;
            List<PhotographyVoteCount> listPv = PhotographyVoteCount.dao.find("SELECT * FROM photography_vote_count WHERE target_id=?",pc.getId());
            if(listPv !=null ){
                voteCount = listPv.size();
            }
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("content",pc);
            map.put("voteCount",voteCount);
            map.put("ranking",i);
            i++;
            listMap.add(map);
        }
        returnSuccessJson(listMap);
    }



    protected void renderData(int code, String message) {
        Ret ret = Ret.create("ReturnCode", code);
        if (StrKit.notBlank(message)) {
            ret.put("AlertMessage", message);
        }
        super.renderJson(ret.getData());
    }
}
